package com.strongbj.iot.devices.ru.response.handle;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.MessageHandleContext;
import com.strongbj.iot.devices.ru.message.RUMessage;
import com.strongbj.iot.devices.ru.message.RuMessageFactory;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * RU1000应答处理的上下文
 * 
 * @author yuzhantao
 *
 */
public class RUResponseHandleContext extends SimpleChannelInboundHandler<RUMessage> {
	private static Logger logger = LogManager.getLogger(RUResponseHandleContext.class.getName());
	private MessageHandleContext<RUMessage, Object> messageHandleContext;
	public static final ChannelGroup channels = new DefaultChannelGroup("RU1000ChannelGroup",
			GlobalEventExecutor.INSTANCE);

	public RUResponseHandleContext() {
		super();
		this.messageHandleContext = new MessageHandleContext<>();
		this.messageHandleContext.addHandleClass(new AlarmInfoHandle());
//		this.messageHandleContext.addHandleClass(new CabinetDoorStateHandle());
		this.messageHandleContext.addHandleClass(new UInfoHandle());
		this.messageHandleContext.addHandleClass(new GetTemperatureHandle());
	}
	RuMessageFactory ruMessageFactory = new RuMessageFactory();
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("RU1000设备已连接" + ctx.channel().remoteAddress().toString());
		channels.add(ctx.channel());
		
//		Timer timer = new Timer();// 实例化Timer类
//        timer.schedule(new TimerTask() {
//            public void run() {
//            	try {
//            		RuMessageFactory.sendReinventoryCommandToRU1000(ctx, "FFFFFF"); // 第一次启动时向RU1000下发盘点命令
//        		} catch (Exception e) {
//        			logger.error("RU1000连接后，下发盘点命令异常。", e);
//        		}
//            }
//        }, 30000);// 延时10秒后进行连接触发的盘点操作
		
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.info("RU1000设备已断开" + ctx.channel().remoteAddress().toString());
		this.messageHandleContext.clearHandleClass();
		super.channelInactive(ctx);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RUMessage msg) throws Exception {
		if (msg == null)
			return;
		InetSocketAddress client = (InetSocketAddress) ctx.channel().remoteAddress();
		logger.info("RU上报数据,IP地址:" + client.getAddress().getHostAddress());

		this.messageHandleContext.handle(ctx, msg); // 处理RU1000消息
	}

}
